var ns;
app = new Vue({
    el: '#app',
    data: {
        IsEdit: false,
        MeterType: 1,//1 房间表 2公表 3总表
        showsearch: false,
        showsearchmonth: false,
        showsearchparam: false,
        form: {
            keywords: '',
            startMonth: '2024-01-22',
            MeterTypeID: 0,
            MeterTypeIDs: [],
        },
        minDate: new Date(),
        maxDate: new Date(),
        currentDate: 0,
        searchbar_click: false,
        MeterTypeList: [
            { ID: 0, Name: '全部' },
            { ID: 2, Name: '电表' },
            { ID: 1, Name: '水表' },
            { ID: 3, Name: '气表' },
        ],
        list: [],
        chooseList: [],
        IsTwoOpenWin:false,
    },
    methods: {
        //限制输入两位小数
        onkeyupreadnumber(item) {
            var that = this;
            var str = item.MeterEndPoint;
            var len1 = str.substr(0, 1);
            var len2 = str.substr(1, 1);
            //如果第一位是0，第二位不是点，就用数字把点替换掉
            if (str.length > 1 && len1 == 0 && len2 != ".") {
                str = str.substr(1, 1);
            }
            //第一位不能是.
            if (len1 == ".") {
                str = "";
            }
            //限制只能输入一个小数点
            if (str.indexOf(".") != -1) {
                var str_ = str.substr(str.indexOf(".") + 1);
                if (str_.indexOf(".") != -1) {
                    str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
                }
            }
            //正则替换，保留数字和小数点
            str = (str.match(/^\d*(\.?\d{0,2})/g)[0]) || '';
            item.MeterEndPoint = str;
            //计算实际用量
            //抄表用量-MeterCalPoint
            if (item.MaxMeterEndPoint != undefined && item.MaxMeterEndPoint) {
                item.MeterCalPoint = (item.MaxMeterEndPoint - item.MeterStartPoint + item.MeterEndPoint) * item.MeterCoefficient;
            }
            else {
                item.MeterCalPoint = (item.MeterEndPoint - item.MeterStartPoint) * item.MeterCoefficient;
            }
            //耗损用量-MeterLossPoint 
            if (item.MeterLossPercent != undefined && item.MeterLossPercent > 0) {
                item.MeterLossPoint = ((item.MeterCalPoint * item.MeterLossPercent) / 100).toFixed(2);
            }
            //维护用量-MeterMaintainPoint
            if (item.MeterMaintainPercent != undefined && item.MeterMaintainPercent > 0) {
                item.MeterMaintainPoint = ((item.MeterCalPoint * item.MeterMaintainPercent) / 100).toFixed(2);
            }
            //扣减用量-ReducePoint?   倍率-MeterCoefficient
            //MeterFinalPoint-实际用量
            item.MeterFinalPoint = (Number(item.MeterCalPoint) + Number(item.MeterLossPoint) + Number(item.MeterMaintainPoint)).toFixed(2);
            // item.MeterFinalPoint = item.MeterCalPoint + item.MeterLossPoint + item.MeterMaintainPoint - item.ReducePoint;     
            that.checkOldPoint();      
        },
        //判断读数存在变更、但是未保存
        checkOldPoint(){
            var that = this;
            if (that.chooseList.length > 0) {
                that.chooseList.forEach((item) => {
                    if (Number(item.oldMeterEndPoint) != Number(item.MeterEndPoint)) {
                        that.IsTwoOpenWin = true;
                        return;
                    }
                });
            }
        },
        onConfirm(day) {
            var that = this;
            var nowdate = moment(day).format('YYYY-MM-DD');
            that.form.startMonth = nowdate;
            that.do_search();
        },
        get_data: function () {
            var that = this;
            // if (that.searchbar_click) {
            //     that.searchbar_click = false;
            //     if (!that.form.keywords) {
            //         api.toast({
            //             msg: '请输入关键字',
            //             duration: 2000,
            //             location: 'bottom'
            //         });
            //         return;
            //     }
            // }
            //filter 查询 that.form.keywords  资源编号、仪表编号、仪表名称  表类型
            let resultData = that.chooseList;
            if (that.IsEdit) {
                that.list = resultData;
            }
            else {
                that.list = resultData.filter((e) => {
                    if (that.form.MeterTypeID == 0) {
                        return e.Name.trim().indexOf(that.form.keywords) > -1 || e.MeterNumber.trim().indexOf(that.form.keywords) > -1 || e.MeterName.trim().indexOf(that.form.keywords) > -1;
                    }
                    else {
                        return that.form.MeterTypeID == e.MeterCategoryID && (e.Name.trim().indexOf(that.form.keywords) > -1 || e.MeterNumber.trim().indexOf(that.form.keywords) > -1 || e.MeterName.trim().indexOf(that.form.keywords) > -1);
                    }
                });
            }
        },
        doSelectMeterType: function (ID) {
            var that = this;
            that.form.MeterTypeID = ID;
            that.form.MeterTypeIDs = [];
            that.form.MeterTypeIDs.push(ID);
            that.showsearchparam = false;
            that.searchbar_click = false;
            that.do_search();
            ns.init_search();
        },
        doSelectSearchParam: function (type) {
            var that = this;
            if (type == 1) { //筛选
                that.showsearchparam = !that.showsearchparam;
                that.showsearchmonth = false;
            }
            if (type == 2) { //按月
                that.showsearchparam = false;
                that.showsearchmonth = !that.showsearchmonth;

            }
            that.showsearch = that.showsearchparam || that.showsearchmonth;
            if (type == 2) { //按月 用的van-popup 自带了遮罩
                that.showsearch = false;
            }
        },
        doHideSearch: function () {
            var that = this;
            that.showsearchparam = false;
            that.showsearchmonth = false;
            that.showsearch = false;
            that.showPopover = false;
        },
        do_search: function () {
            var that = this;
            that.searchbar_click = true;
            that.doHideSearch();
            that.get_data();
        },
        onChooseMeterDel(row) {
            var that = this;
            api.confirm({
                title: '提示信息',
                msg: '确认要将仪表移除本次抄表',
                buttons: ['确认', '取消']
            }, function (ret, err) {
                if (ret) {
                    if (ret.buttonIndex == 1) {
                        //是否添加触发事件  更新上个页面的选中数据
                        let findIndex = that.chooseList.findIndex((item) => {
                            return item.ID == row.ID && item.MeterID == row.MeterID;
                        });
                        let findIndexlist = that.list.findIndex((item) => {
                            return item.ID == row.ID && item.MeterID == row.MeterID;
                        });
                        if (findIndex > -1) {
                            that.chooseList.splice(findIndex, 1);//删除 
                        }
                        if (findIndexlist > -1) {
                            that.list.splice(findIndexlist, 1);//删除
                        }
                    }
                }
            });
        },
        // 保存读数
        do_save: function () {
            var that = this;
            //判断
            let findIndex = that.chooseList.findIndex((item) => {
                return item.MeterEndPoint == '' || item.MeterEndPoint == 0;
            });
            if (findIndex > -1) {
                api.alert({
                    title: '提示信息',
                    msg: '存在未录入读数的仪表，请先录入读数',
                }, function () {
                });
                return;
            }
            for (var i = 0; i < that.chooseList.length; i++) {
                if (that.chooseList[i].MeterEndPoint < that.chooseList[i].MeterStartPoint) {
                    api.toast({
                        msg: '"' + that.chooseList[i].MeterName + '"当前录入读数不能小于上次抄表读数',
                        duration: 3000,
                        location: 'bottom'
                    });
                    return;
                }
            }
            let findIndexFact = that.chooseList.findIndex((item) => {
                return item.MeterFinalPoint <= 0;
            });
            if (findIndexFact > -1) {
                api.confirm({
                    title: '提示信息',
                    msg: '存在实际用量为0的仪表，是否要进行保存？',
                    buttons: ['保存', '取消']
                }, function (ret, err) {
                    if (ret) {
                        if (ret.buttonIndex == 1) {
                            that.doSaveRead();
                        }
                        return;
                    }
                });
                return;
            }
            that.doSaveRead();
        },
        //保存读数
        doSaveRead() {
            var that = this;
            var options = {};
            //编辑读数
            if (that.IsEdit) {
                options.action = "savechargemetermulpoing";
            }
            else {
                options.action = "savemeterroompointadd";
                options.writeDate = that.form.startMonth;
            }
            options.Type = that.MeterType;
            var dataList = [];
            that.chooseList.forEach((item, index, array) => {
                var datamodel = { ID: 0, MeterStartPoint: 0, MeterEndPoint: 0, MeterCalPoint: 0, MeterLossPoint: 0, MeterMaintainPoint: 0, MaxMeterEndPoint: 0, MeterRemark: "" };
                datamodel.ID = item.ID;
                datamodel.MeterStartPoint = item.MeterStartPoint;
                datamodel.MeterEndPoint = item.MeterEndPoint;
                datamodel.MeterCalPoint = item.MeterCalPoint;
                datamodel.MeterLossPoint = item.MeterLossPoint;
                datamodel.MeterMaintainPoint = item.MeterMaintainPoint;
                datamodel.MaxMeterEndPoint = item.MaxMeterEndPoint;
                datamodel.MeterRemark = item.MeterRemark;
                dataList.push(datamodel);
            });
            options.dataList = JSON.stringify(dataList);
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    api.sendEvent({
                        name: 'reload_chhoose_read'
                    })
                    setTimeout(function () {
                        api.closeWin();
                    }, 2000);
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 3000,
                        location: 'bottom'
                    });
                    return;
                }
            });
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    app.form.startMonth = api.pageParam.startMonth;
    app.chooseList = api.pageParam.chooseList;
    app.IsEdit = api.pageParam.IsEdit || false;
    app.MeterType = api.pageParam.MeterType || 1;
    if (app.chooseList.length > 0) {
        for (var i = 0; i < app.chooseList.length; i++) {
            app.chooseList[i].oldMeterEndPoint = app.chooseList[i].MeterEndPoint;
        }
    }

    app.doSelectMeterType(0);
    ns.init_search();
    // ns.init_pull();

    //返回时判断数据-读数存在变更、但是未保存 给予二次弹窗
    api.addEventListener({
        name: 'do_publictopleft',
    }, function (ret, err) {
        if (!app.IsTwoOpenWin) {
            api.closeWin();
            return;
        }
        api.confirm({
            title: '提示信息',
            msg: '确认是否需要保存录入读数',
            buttons: ['确认', '取消']
        }, function (ret, err) {
            if (ret) {
                if (ret.buttonIndex == 1) {
                    app.do_save();
                    return;
                }
                api.closeWin();
            }
        });
        
    });
};
